<!--
  文件上传
  使用方式:
    <base-file-upload :files="fileList" :show-file-list="false" @upload="onUpload"></base-file-upload>
-->
<template>
  <el-upload
    multiple
    action="."
    accept=".xls,.xlsx,.doc,.docx,.pdf"
    :limit="limit"
    :file-list="fileList"
    :disabled="disabled"
    :show-file-list="showFileList"
    :before-upload="onBeforeUpload"
    :http-request="handleUploadFile"
    :before-remove="beforeRemove"
    :on-remove="handleRemove"
    :on-exceed="handleExceed">
    <el-button size="small" type="primary" :disabled="disabled">附件上传</el-button>
    <div v-if="isTip" slot="tip" class="el-upload__tip">只能上传 xls/xlsx/doc/docx/pdf 文件，且不超过50MB</div>
  </el-upload>
</template>

<script>
import { uploadFile, deleteFile } from '../../apis/common-controller';

export default {
  name: 'base-file-upload',
  props: {
    files: {
      type: Array,
      default: () => [],
    },
    limit: {
      type: Number,
      default: 5,
    },
    isTip: {
      type: Boolean,
      default: false,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    // 是否显示上传文件列表
    showFileList: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      fileList: [],
    };
  },
  watch: {
    files: {
      handler(newVal) {
        if (newVal) {
          this.fileList = newVal.map(file => ({ name: file.fileName, ...file }));
        } else {
          this.fileList = [];
        }
      },
      immediate: true,
      deep: true,
    },
  },
  methods: {
    /**
     * 文件上传前的钩子函数
     * @description  支持的文件格式：.xls,.xlsx,.doc,.docx,.pdf
     */
    onBeforeUpload(file) {
      // 最大支持上传文件大小为 50MB
      const isLimit50M = file.size / 1024 / 1024 < 50;
      const extensionName = file.name.substring(file.name.lastIndexOf('.') + 1);
      const isXls = extensionName === 'xls';
      const isXlsx = extensionName === 'xlsx';
      const isDoc = extensionName === 'doc';
      const isDocx = extensionName === 'docx';
      const isPdf = extensionName === 'pdf';

      if (!isXls && !isXlsx && !isDoc && !isDocx && !isPdf) {
        this.$message.error('上传文件必须是 xls/xlsx/doc/docx/pdf 格式!!');
      }

      if (!isLimit50M) {
        this.$message.error('上传文件大小不能超过 50MB!');
      }

      return (isXls || isXlsx || isDoc || isDocx || isPdf) && isLimit50M;
    },

    /**
     * 自定义文件上传
     */
    handleUploadFile(result) {
      const file = result.file;
      // 最大支持上传文件大小为 50MB
      const isLimit50M = file.size / 1024 / 1024 < 50;
      if (!isLimit50M) {
        this.$message.error('上传文件大小不能超过 50MB!');
        return false;
      }

      const formData = new FormData();
      formData.append('file', file);

      uploadFile(formData).then(res => {
        this.$message.success('上传成功!');
        const fileList = res.map(file => ({ name: file.fileName, ...file }));
        this.fileList = [...this.fileList, ...fileList];
        this.$emit('upload', this.fileList);
      }).catch(err => {
        // this.fileList = [];
        this.$message.error(err.data.message);
      });
    },

    beforeRemove(file) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },

    /**
     * 删除文件
     */
    handleRemove(file, fileList) {
      if (file.fileId) {
        deleteFile(file.fileId).then(() => {
          this.fileList = fileList;
          this.$emit('upload', fileList);
        });
      }
    },

    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 ${this.limit} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length +
        fileList.length} 个文件`,
      );
    },
  },
};
</script>

<style lang="less" scoped></style>
